﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.Threading;
using System.Windows.Forms;

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;
using System.Timers;

namespace CivCraft
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    /// 

    public class Unit
    {
        public Map Map
        {
            get { return map; }
        }
        Map map;

        public int posX;
        public int posY;
        public int targetX;
        public int targetY;
        public int[,] movable;


        private void unitCreate(int type, int x, int y)
        {

            //Call Server for 





        }
        public void getState(char type, int x, int y, System.Net.Sockets.TcpClient clientSocket)
        {
            NetworkStream sendingMsg = clientSocket.GetStream();

            if (type == 'N')
            {
                byte[] outStream = System.Text.Encoding.ASCII.GetBytes("CREATE_UNIT|" + x + "," + y + "$");
                sendingMsg.Write(outStream, 0, outStream.Length);
                sendingMsg.Flush();

                //send packet; recieve status
            }

            return;
        }
        private void unitMove() { }
        private void unitSkill() { }


        private void SendMsg(int type, int com, int px, int py, int tx, int ty) { }

        public Unit()
        {
            // TODO: Construct any child components here
        }

        /// <summary>
        /// Allows the game component to perform any initialization it needs to before starting
        /// to run.  This is where it can query for any required services and load content.
        /// </summary>


        /// <summary>
        /// Allows the game component to update itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        public void Update(GameTime gameTime)
        {
            // TODO: Add your update code here


        }
        public void Draw(GameTime gameTime, SpriteBatch spriteBatch)
        {

        }
    }
    

    public class Game1 : Microsoft.Xna.Framework.Game
    {
        System.Net.Sockets.TcpClient clientSocket = new System.Net.Sockets.TcpClient();
        

        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        SpriteFont spriteFont;
        //Texture2D defTile;
        Texture2D highlight_Norm;
        Texture2D highlight_Create;
        
        Texture2D unit_F;
        Texture2D unit_A;
        Texture2D unit_S;
        Texture2D unit_P;
        Texture2D def_Fire;
        
        private const int TrgatFramerate = 60;
        private const int BackBufferWidth = 720;
        private const int BackBufferHeight = 636;

        private TimeSpan timeRemaining;

        //private List<Unit> units = new List<Unit>();

        private Unit units;

        //private List<Texture2D> defTile = new List<Texture2D>[15]();
        Texture2D[] defTile = new Texture2D[16];
        private Map map;

        public int mouseX;
        public int mouseY;
            
        public int Height=7;
        public int Width=15;

        public int tsize = 48;
        public int goldLeft = 1000;


        private bool showHeight=false;
        private bool ismyTurn = true;

        private Random random = new Random(354668); // Arbitrary, but constant seed

        public void ReceiveMsg()
        {
        /*    NetworkStream serverStream1 = clientSocket.GetStream();
            for (;;)
            {
                byte[] inStream = new byte[10000];
                serverStream1.Read(inStream, 0, (int)clientSocket.ReceiveBufferSize);
                string returndata = System.Text.Encoding.ASCII.GetString(inStream);
                if (returndata)
                {
                    string.Compare(



                }


            }*/
        }

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            graphics.PreferredBackBufferHeight = BackBufferHeight;
            graphics.PreferredBackBufferWidth = BackBufferWidth;
            IsMouseVisible = true;
            map = new Map(Services);
            units = new Unit();
            Content.RootDirectory = "Content";
            timeRemaining = TimeSpan.FromMinutes(2.0);

            clientSocket.Connect("127.0.0.1", 8888); //풀기
            
            Thread recv_msg = new Thread(new ThreadStart(ReceiveMsg));
            recv_msg.Start();
            
            //socket

            
            //NetworkStream serverStream = clientSocket.GetStream();
          

        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here

            base.Initialize();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);
            spriteFont = Content.Load<SpriteFont>("Fonts/Hud");
            for (int i = 1; i < 16; i++)
            {
                defTile[i] = Content.Load<Texture2D>("Tiles/defTile0" + i);
            }

            //Selection
            highlight_Norm = Content.Load<Texture2D>("Tiles/highlight_Norm");
            highlight_Create = Content.Load<Texture2D>("Tiles/highlight_Create");
            //Unit
            unit_F = Content.Load<Texture2D>("Units/unit_F");
            unit_A = Content.Load<Texture2D>("Units/unit_A");
            unit_S = Content.Load<Texture2D>("Units/unit_S");
            unit_P = Content.Load<Texture2D>("Units/unit_P");
            def_Fire = Content.Load<Texture2D>("Tiles/defTile_Fire");
            //Unit Type 1 : def/F  2 : def/P  3: att/F  4: att/A 5: att/S



            // TODO: use this.Content to load your game content here
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            
            HandleInput();
            timeRemaining -= gameTime.ElapsedGameTime;
            map.Update(gameTime);

            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == Microsoft.Xna.Framework.Input.ButtonState.Pressed)
                this.Exit();

            // TODO: Add your update logic here

        //    foreach (Unit unit in units) { }



            base.Update(gameTime);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        private void HandleInput()
        {
            KeyboardState kbstate = Keyboard.GetState();
            mouseX = Mouse.GetState().X;   
            mouseY = Mouse.GetState().Y;
            mouseX = mouseX / 48;
            mouseY = mouseY / 48;



            if (Mouse.GetState().LeftButton == Microsoft.Xna.Framework.Input.ButtonState.Pressed)
            {
                //Window.Title = "X : " + mouseX + " Y : " + mouseY;
                if (ismyTurn == true)
                {
                    if (map.statCheck(mouseX,mouseY) == 'N')
                    {
                        units.getState('N', mouseX, mouseY, clientSocket);
                    }

                    



                }




            }
            if (kbstate.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.Tab)) { showHeight = true; }
            else{ showHeight=false;}


        }

        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.White);
            spriteBatch.Begin();
            // TODO: Add your drawing code here
            

            //Draw background/selection

            for (int y = 0; y < Height; y++)
            {
                for (int x = 0; x < Width; x++)
                {
                    Texture2D texture;
                    Texture2D dup;
                    dup = defTile[map.GetCells(x,y)];
                    texture = defTile[map.GetCells(x, y)];
                    
                    Vector2 position = new Vector2(x, y) * tsize;
                    Color hColor;
                    hColor = Color.White;
                    
                    spriteBatch.Draw(texture, position, hColor);
                    if (x == mouseX && y == mouseY)
                    {
                        if (map.statCheck(x, y) == 'N') { dup = highlight_Create; }
                        else
                        {
                            dup = highlight_Norm;
                        }
                    }
                    spriteBatch.Draw(dup, position, hColor);
                    //Draw Unit//
                    if (map.statCheck(x, y) == '1' || map.statCheck(x,y) =='3')
                    {
                        spriteBatch.Draw(unit_F, position, Color.Red);
                    }
                    if (map.statCheck(x, y) == '4')
                    {
                        spriteBatch.Draw(unit_A, position, Color.Red);
                    }
                    if (map.statCheck(x, y) == '5')
                    {
                        spriteBatch.Draw(unit_S, position, Color.Red);
                    }
                    if (map.statCheck(x, y) == '2')
                    {
                        spriteBatch.Draw(unit_P, position, Color.Red);
                    }
                    if (map.statCheck(x, y) == 'B')
                    {
                        spriteBatch.Draw(def_Fire, position, Color.White);
                    }


                    //Tab//
                    if (showHeight == true)
                    {
                        spriteBatch.DrawString(spriteFont, map.GetCells(x, y).ToString(), position, Color.Black);
                    }
                }
            }



            //
            Rectangle titleSafeArea = GraphicsDevice.Viewport.TitleSafeArea;
            Vector2 timeLocation = new Vector2(titleSafeArea.X, 340);
            Vector2 goldLocation = new Vector2(600, 340);
            Vector2 center = new Vector2(titleSafeArea.X + titleSafeArea.Width / 2.0f,
                                         titleSafeArea.Y + titleSafeArea.Height / 2.0f);
            string timeString = "TIME: " + timeRemaining.Minutes.ToString("00") + ":" + timeRemaining.Seconds.ToString("00");
            Color timeColor = Color.Red;

            spriteBatch.DrawString(spriteFont, timeString, timeLocation, timeColor);
            spriteBatch.DrawString(spriteFont, "GOLD: "+goldLeft.ToString(), goldLocation, timeColor);

            spriteBatch.End();
            base.Draw(gameTime);
        }
    }
}
